package listbyorder.access201_300.test236;

import listbyorder.utils.TreeNode;

import java.util.*;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/26 20:02
 */
public class Solution1 {

    // 方法一：递归求解
    // 1 判断p和q分别在root的哪个子树上面，， 左子树/右子树
    // 2 如果一左一右，那么根节点root一定是最近的祖先
    // 3 如果p和q都在root的左子树上，那么根节点页一定在左子树上面，递归到左子树
    // 4 如果p和q都在root的右子树上，那么根节点页一定在右子树上面，递归到右子树
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == p || root == q) return root;
        boolean pLeft = false;
        boolean qLeft = false;
        TreeNode left = root.left;
        Stack<TreeNode> stack = new Stack<>();
        while (left != null || !stack.isEmpty()) {
            while (left != null) {
                stack.push(left);
                left = left.left;
            }
            left = stack.pop();
            if (left == p) {
                pLeft = true;
            }
            if (left == q) {
                qLeft = true;
            }
            left = left.right;
        }

        if (pLeft && qLeft) {
            return lowestCommonAncestor(root.left, p, q);
        } else if (!pLeft && !qLeft) {
            return lowestCommonAncestor(root.right, p, q);
        } else {
            return root;
        }
    }


}
